import { NestFactory } from '@nestjs/core';
import { LoggerService } from '@nestjs/common'
import { ValidationPipe } from 'src/share/pipe/validate';
import { AppModule } from './app.module';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { WsAdapter } from '@nestjs/platform-ws';

async function bootstrap() {
  const instance = express
  const allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000'); //自定义中间件，设置跨域需要的响应头。
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Access-Control-Allow-Credentials", true);
    next();
  }
  
  const app = await NestFactory.create(AppModule);

  // 建立Swagger頁面設定檔  
  const userApiOptions = new DocumentBuilder()
            .setTitle('User API Doc')
            .setDescription('User API Info')
            .setVersion('2.0')
            .addBearerAuth()
            .addTag('user') // match tags in controllers
            .build()
  
  // 沒有指定第三個參數代表所有Module的controller都會被偵測
  const userApiDocument= SwaggerModule.createDocument(app, userApiOptions)
  // 指定Swagger API頁面路徑及傳入nest app及頁面設定檔
  SwaggerModule.setup('v1/api/', app, userApiDocument)

  await app.use(allowCrossDomain)
  await app.use(bodyParser.urlencoded({
    extended: true
  }))
  await app.useGlobalPipes(
    new ValidationPipe()
  )
  app.useWebSocketAdapter(new WsAdapter(app));
  await app.listen(3000)
}
bootstrap()
